import axios, { AxiosRequestConfig } from 'axios'
import {
  commonRequestConfig,
  commonRequestInterceptors,
  commonResponseInterceptors,
} from './commonConfig.ts'

import { RequestInterceptor, ResponseInterceptor } from './types.ts'

// 创建请求实例，允许不同的实例设置不同的配置，这些配置会和默认配置合并
function createInstance(
  config: AxiosRequestConfig = {},
  requestInterceptors: RequestInterceptor[] = [],
  responseInterceptors: ResponseInterceptor[] = [],
) {
  // 创建实例
  const instance = axios.create({
    ...commonRequestConfig,
    ...config,
  })

  // 获取通用以及自定义的请求拦截器
  const allRequestInterceptors: RequestInterceptor[] = [
    ...commonRequestInterceptors,
    ...requestInterceptors,
  ]

  // 设置所有请求拦截器
  allRequestInterceptors.forEach((requestInterceptor) => {
    instance.interceptors.request.use(requestInterceptor.onFulfilled, requestInterceptor.onRejected)
  })

  // 获取通用以及自定义的响应拦截器
  const allResponseInterceptors: ResponseInterceptor[] = [
    ...commonResponseInterceptors,
    ...responseInterceptors,
  ]

  // 设置所有响应拦截器
  allResponseInterceptors.forEach((responseInterceptor) => {
    instance.interceptors.response.use(
      responseInterceptor.onFulfilled,
      responseInterceptor.onRejected,
    )
  })

  /**
   * @param {string} url
   * @param {object} data
   * @param {object} headers
   */

  function post<T>(url: string, data = {}, headers = {}): Promise<T> {
    return instance({
      method: 'post',
      url,
      data,
      headers,
    })
  }

  /**
   * @param {string} url
   * @param {object} params
   */
  function get<T>(url: string, params = {}, headers = {}): Promise<T> {
    return instance({
      method: 'get',
      url,
      params,
      headers,
    })
  }

  return {
    instance,
    post,
    get,
  }
}

export default createInstance
